//
//  PPHomeViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/9/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "HomeHeadModel.h"
#import "HomeProductItemModel.h"

#import "HomeBannerCell.h"
#import "HomeDistanceCell.h"
#import "HomeNormalImageCell.h"
#import "HomeMainIconItemCell.h"
#import "ProductListTableViewCell.h"

#import "PPHomeViewController.h"
#import "GoodDetailViewController.h"
#import "MessageCenterViewController.h"

#import "HomeSubscriptButton.h"

#import "OYCountDownManager.h"

NSString *const k_pphomeProductItemSource = @"k_pphomeProductItemSource";

@interface PPHomeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) HomeHeadModel         *headModel;

@property (nonatomic, strong) NSMutableArray<HomeProductItemModel *>*productListArray;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) CGFloat mainIconItemHeight;

@property (nonatomic, strong) HomeSubscriptButton *messageItem;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation PPHomeViewController

- (void)dealloc {
    [kCountDownManager removeSourceWithIdentifier:k_pphomeProductItemSource];
    [kCountDownManager invalidate];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PP_AppWillEnterForegroundNoti" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForegroundRefreshNoti:) name:@"PP_AppWillEnterForegroundNoti" object:nil];
}

//修改时间进app刷新首页
-(void)enterForegroundRefreshNoti:(NSNotification *)Noti {
    
    [self request_HomeData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [self initParam];
    [self request_HomeData];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    [self refreshUnReadMsgCount];
    [kCountDownManager start];
    [kCountDownManager addSourceWithIdentifier:k_pphomeProductItemSource];
}

#pragma mark 首页发生刷新行为时，reload定时器
- (void)reloadTime {
    [kCountDownManager reloadSourceWithIdentifier:k_pphomeProductItemSource];
}

#pragma mark 刷新未读消息数
- (void)refreshUnReadMsgCount {

    [self.messageItem setCountNum:0];
}

- (void)initParam {
    self.pageNum = 1;
    self.pageSize = 100;
}

#pragma mark 去消息中心
- (void)goMsgCenter {
    [self.navigationController pushViewController:[MessageCenterViewController new] animated:YES];
}

- (void)request_HomeData {
    [self reloadTime];

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"curPage"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_HOME_ALL];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    //model初始化
                    self.headModel = [[HomeHeadModel alloc] init];
                    self.headModel.bannerModel = [[HomeHeadListModel alloc] init];
                    self.headModel.notiMsgModel = [[HomeHeadListModel alloc] init];
                    self.headModel.mainIconModel = [[HomeHeadListModel alloc] init];
                    
                    
                    BOOL hasCoupon = [[resultDic valueForKey:@"hasCoupon"] boolValue];
                    if (hasCoupon && [Utilities checkOnceADayWithKey:TT_ONCE_ACTION_HOME_COUPON]) {
                        
                        [self alert:@"您有一次低价竞拍 一拍必得专场商品的机会，是否立即使用" leftTitle:@"取消" Action:^(UIAlertAction * _Nonnull action) {
                        } rightTitle:@"使用" Action:^(UIAlertAction * _Nonnull action) {
                            [self.navigationController changeNormalNavigation];
                            [self.navigationController popToRootViewControllerAnimated:NO];
                            [PPTabBarController setCurrentIndex:PPTabbarIndexTypeShop];
                        }];
                    }
                    
                    //banner塞数据
                    self.headModel.bannerModel.itemArray = @[].mutableCopy;
                    NSArray *bannerArray = [resultDic valueForKey:@"bannerRes"];
                    if ([bannerArray isKindOfClass:[NSArray class]]) {
                        
                        for (int i = 0; i<bannerArray.count; i++) {
                            NSDictionary *bannerDic = [bannerArray objectAtIndex:i];
                            HomeHeadItemModel *model = [[HomeHeadItemModel alloc] init];
                            model.itemActionModel = [[PP_jumpModel alloc] init];
                            model.itemActionModel.type = CommentClickType_HtmlPage;
                            model.itemActionModel.ID = [bannerDic valueForKey:@"externalLinks"];
                            model.itemImagePath = [bannerDic valueForKey:@"imagePath"];
                            
                            [self.headModel.bannerModel.itemArray addObject:model];
                        }
                    }

                    //icon塞数据
                    self.headModel.mainIconModel.itemArray = @[].mutableCopy;
                    NSArray *mainIconArray = [resultDic valueForKey:@"sysDocRes"];
                    if ([mainIconArray isKindOfClass:[NSArray class]]) {
                        for (int i = 0; i < mainIconArray.count; i++) {
                            
                            NSDictionary *mainIconDic = [mainIconArray objectAtIndex:i];
                            HomeHeadItemModel *model = [[HomeHeadItemModel alloc] init];
                            model.itemActionModel = [[PP_jumpModel alloc] init];
                            model.itemActionModel.type = CommentClickType_HtmlPage;
                            model.itemActionModel.ID = [mainIconDic valueForKey:@"externalLinks"];
                            model.itemImagePath = [mainIconDic valueForKey:@"imagePath"];
                            model.itemTitle = [mainIconDic valueForKey:@"title"];
                            [self.headModel.mainIconModel.itemArray addObject:model];
                        }
                        
                        //计算mainicon区域的高度
                        NSInteger lineCount  = self.headModel.mainIconModel.itemArray.count/4 + (self.headModel.mainIconModel.itemArray.count%4>0?1:0);
                        self.mainIconItemHeight = lineCount * homeMainIconHeight;
                    }

                    //product塞数据
                    if (self.pageNum == 1) {
                        [self.productListArray removeAllObjects];
                    }
                    NSArray *productArray = [resultDic valueForKey:@"auctionInfoRes"];
                    
                    if ([productArray isKindOfClass:[NSArray class]]) {
                        
                        if (productArray.count < self.pageSize) {
                            [self.tableview.mj_footer endRefreshingWithNoMoreData];
                        }
                        
                        for (int i = 0; i < productArray.count; i++) {
                            NSDictionary *productDic = [productArray objectAtIndex:i];
                            HomeProductItemModel *productModel = [[HomeProductItemModel alloc] init];
                            productModel.productID = [productDic valueForKey:@"id"];
                            productModel.productName = [productDic valueForKey:@"goodsName"];
                            productModel.productImage = [productDic valueForKey:@"coverImgPath"];
                            
                            productModel.auctionPrice = [[productDic valueForKey:@"goodsStartingPrice"] doubleValue];
                            productModel.marketPrice = [[productDic valueForKey:@"goodsMarketPrice"] doubleValue];

                            productModel.goodDetailType =(PPGoodDetailType)[[productDic valueForKey:@"goodDetailType"] integerValue];

                            productModel.beginTimestamp = [[productDic valueForKey:@"startTime"] doubleValue];
                            productModel.endTimestamp = [[productDic valueForKey:@"endTime"] doubleValue];//2019-08-02
                            
                            productModel.countDownSource = k_pphomeProductItemSource;
                            [self.productListArray addObject:productModel];
                        }
                    }
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
                
                WEAKSELF
                [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                    [weakSelf request_HomeData];
                }];
                
            }
            
            [self.tableview reloadData];

        } else {
            
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
            [SVProgressHUD dismissWithDelay:1];
        }
        

    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismissWithDelay:0.5];

        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_HomeData];
        }];
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case PPHomeCellType_BannerItem:{
                
                HomeBannerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeBannerCellID" forIndexPath:indexPath];
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                [cell configBannerCellWithImageArray:[HomeHeadListModel getImageArrayWith:self.headModel.bannerModel.itemArray]];
                
                cell.CycleImgClickedBlock = ^(NSInteger index) {
                    
                    PP_jumpModel *model = [[PP_jumpModel alloc] init];
                    model.type = self.headModel.bannerModel.itemArray[index].itemActionModel.type;
                    model.ID = self.headModel.bannerModel.itemArray[index].itemActionModel.ID;
                    [[TTJumpManager share] pushViewControllerWithModel:model];
                    
                };
                return cell;
                
            } break;
            case PPHomeCellType_MainIconItem:{
                
                HomeMainIconItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeMainIconItemCellID" forIndexPath:indexPath];
                
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                [cell fillCellWithModel:self.headModel.mainIconModel];
                
                cell.MainIconClickedBlock = ^(NSInteger index) {
                    
                    PP_jumpModel *model = [[PP_jumpModel alloc] init];
                    model.type = self.headModel.mainIconModel.itemArray[index].itemActionModel.type;
                    model.ID = self.headModel.mainIconModel.itemArray[index].itemActionModel.ID;
                    [[TTJumpManager share] pushViewControllerWithModel:model];
                    
                };
                
                return cell;
                
            } break;
            case PPHomeCellType_NormalImageItem:{
                
                HomeNormalImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeNormalImageCellID" forIndexPath:indexPath];
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                
                return cell;
                
            } break;
            default:{
                
                HomeDistanceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeDistanceCellID" forIndexPath:indexPath];
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                
                return cell;
                
            } break;
        }
    } else {
        
        ProductListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductListTableViewCellID" forIndexPath:indexPath];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        
        if (self.productListArray.count > indexPath.row) {
            [cell fillCellWithModel:self.productListArray[indexPath.row]];
        }
        
        WEAKSELF
        cell.countDownZero = ^(HomeProductItemModel * _Nonnull model) {
            if (indexPath.row < weakSelf.productListArray.count) {
                [weakSelf.productListArray replaceObjectAtIndex:indexPath.row withObject:model];//复用的时候永用到
            }
        };
        
        return cell;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 4;
    } else {
        return self.productListArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {

        switch (indexPath.row) {
            case PPHomeCellType_BannerItem:{

                return PP_Home_Banner_Scale * TTScreenWidth ;
            } break;
            case PPHomeCellType_MainIconItem:{

                return self.mainIconItemHeight;
            } break;
            case PPHomeCellType_NormalImageItem:{

                if (self.productListArray.count > 0) {
                    return homeNormalImageHeight;
                } else {
                    return CGFLOAT_MIN;
                }
                
            } break;
            default:{

                return 10;
            } break;
        }

    } else {
        
        return TTScreenWidth/4 + 16;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        
        if (self.productListArray.count > indexPath.row) {
            GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
            detailVC.goodsID = self.productListArray[indexPath.row].productID;
            detailVC.type = self.productListArray[indexPath.row].goodDetailType;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headview = [[UIView alloc]init];
    headview.backgroundColor = [UIColor blackColor];
    return headview;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor brownColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (void)initView {
    
    self.title = @"拍拍得利";
    
    self.mainIconItemHeight = homeMainIconHeight;
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.messageItem];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.tableview];

    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerClass:[HomeBannerCell class] forCellReuseIdentifier:@"HomeBannerCellID"];
        
        [_tableview registerClass:[HomeMainIconItemCell class] forCellReuseIdentifier:@"HomeMainIconItemCellID"];

        [_tableview registerNib:[UINib nibWithNibName:@"HomeDistanceCell" bundle:nil] forCellReuseIdentifier:@"HomeDistanceCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"ProductListTableViewCell" bundle:nil] forCellReuseIdentifier:@"ProductListTableViewCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"HomeNormalImageCell" bundle:nil] forCellReuseIdentifier:@"HomeNormalImageCellID"];
        
        WEAKSELF
        
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf initParam];
            [weakSelf request_HomeData];
        }];
        
        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_HomeData];
        }];
    }
    return _tableview;
}

- (HomeSubscriptButton *)messageItem {
    if (!_messageItem) {
        _messageItem = [[HomeSubscriptButton alloc] initWithSize:CGSizeMake(40, 40)];
        [_messageItem.topButton setImage:[UIImage imageNamed:@"homeMsg"] forState:UIControlStateNormal];;
        _messageItem.userInteractionEnabled = YES;
        [_messageItem.topButton addTarget:self action:@selector(goMsgCenter) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageItem;
}

- (NSMutableArray<HomeProductItemModel *> *)productListArray {
    if (!_productListArray) {
        _productListArray = @[].mutableCopy;
    }
    return _productListArray;
}

@end
